package com.craftplay.controller;

import com.craftplay.dao.ClassOrderMapper;
import com.craftplay.dao.OrderMapper;
import com.craftplay.model.ClassOrder;
import com.craftplay.model.HostHolder;
import com.craftplay.model.Order;
import com.craftplay.model.Unit;
import com.craftplay.service.MomentService;
import com.craftplay.service.WeixinService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/play/callBack")

public class CallBackController {


    @Autowired
    HostHolder hostHolder;

    @Autowired
    private WxPayService wxService;

    @Autowired
    MomentService momentService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private ClassOrderMapper classOrderMapper;


    /**
     * 支付回调
     */
    @PostMapping("/notify/order")
    public String parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
        final WxPayOrderNotifyResult notifyResult = this.wxService.parseOrderNotifyResult(xmlData);
        // TODO 根据自己业务场景需要构造返回对象
        String outTradeNo = notifyResult.getOutTradeNo();
        Order order = orderMapper.selectByOutTradeNo(outTradeNo);
        if (order.getStatus() == 1) {
            order.setStatus(2);
            order.setPaytime(new Date());
            orderMapper.updateByPrimaryKey(order);

            //如果是课程就创建
            Unit unit = momentService.oneMomentDetail(order.getUnitid());
            if (unit.getKind() == 12) {
                ClassOrder classOrder = new ClassOrder();
                classOrder.setCreateTime(new Date());
                classOrder.setOutTradeNo(outTradeNo);
                classOrder.setClassType(order.getClassType());
                classOrder.setMoney(order.getMoney());
                classOrder.setClassTreeType(order.getClassTreeType());
                classOrder.setPayTime(order.getCreatetime());
                classOrder.setClassStatus(0);//就绪状态
                classOrder.setUnitId(unit.getId());
                classOrder.setUserId(order.getUserid());
                classOrder.setMessage(order.getMessage());
                classOrderMapper.insert(classOrder);
            } else {
                weixinService.sendRedpack(order);
            }
        }
        return WxPayNotifyResponse.success("成功");
    }


}
